package com.ruoyi.asset.controller;

import com.ruoyi.asset.domain.*;
import com.ruoyi.asset.service.*;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Controller
@RequestMapping("/app")
public class AppController extends BaseController {

    @Autowired
    private ServerConfig serverConfig;

    private static final String FILE_DELIMETER = ",";

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private IAstDeviceService deviceService;

    @Autowired
    private IAstSiteService siteService;

    @Autowired
    private IAstSiteRecordService siteRecordService;

    @Autowired
    private IAstTaskUserService taskUserService;

    @Autowired
    private IAstManualService manualService;

    @Autowired
    private IAstStoreroomService storeroomService;

    @Autowired
    private IAstFactoryService factoryService;

    @Autowired
    private ISysNoticeService noticeService;

    @Autowired
    private IAstDeviceRecordService deviceRecordService;

    @RequestMapping("/login")
    @ResponseBody
    public AjaxResult login(String loginName,String password)
    {
        SysUser sysUser = userService.selectUserByLoginName(loginName);
        if(sysUser == null){
            return AjaxResult.error("用户或密码错误");
        }
        if (!passwordService.matches(sysUser, password)){
            return AjaxResult.error("用户或密码错误");
        }
        SysUser returnUser = new SysUser();
        returnUser.setUserId(sysUser.getUserId());
        returnUser.setLoginName(sysUser.getLoginName());
        returnUser.setUserName(sysUser.getUserName());
        returnUser.setDeptId(sysUser.getDeptId());

        return AjaxResult.success("登录成功",returnUser);
    }

    @RequestMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwd(Long userId,String oldPassword, String newPassword)
    {
        SysUser user = userService.selectUserById(userId);
        if (!passwordService.matches(user, oldPassword))
        {
            return error("修改密码失败，旧密码错误");
        }
        if (passwordService.matches(user, newPassword))
        {
            return error("新密码不能与旧密码相同");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), newPassword, user.getSalt()));
        user.setPwdUpdateDate(DateUtils.getNowDate());
        if (userService.resetUserPwd(user) > 0)
        {
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }

    //个人信息
    @RequestMapping("/myInfo")
    @ResponseBody
    public AjaxResult myInfo(Long userId){
        SysUser sysUser = userService.selectUserById(userId);
        SysDept sysDept = deptService.selectDeptById(sysUser.getDeptId());
        List<SysPost> sysPosts = postService.selectPostsByUserId(userId);

        Map retrunMap = new HashMap();
        retrunMap.put("userName",sysUser.getUserName());
        retrunMap.put("phonenumber",sysUser.getPhonenumber());
        retrunMap.put("zhuanye",sysUser.getRemark());
        retrunMap.put("isThird","否");
        if(sysDept !=null){
            if(sysDept.getIsThird().equals("Y")){
                retrunMap.put("isThird","是");
            }else{
                retrunMap.put("isThird","否");
            }
            retrunMap.put("deptName",sysDept.getDeptName());
            retrunMap.put("deptPhone",sysDept.getPhone());
            retrunMap.put("deptAddress",sysDept.getDeptAddress());
        }
        String gangwei = "";
        for(SysPost post : sysPosts){
            if(post.isFlag()==true){
                if(gangwei.equals("")){
                    gangwei = post.getPostName();
                }else{
                    gangwei = gangwei+","+post.getPostName();
                }
            }
        }
        retrunMap.put("zhiwei",gangwei);

        return AjaxResult.success("查询成功",retrunMap);
    }

    //修改手机号
    @RequestMapping("/updateMyPhonenumber")
    @ResponseBody
    public AjaxResult updateMyPhonenumber(Long userId,String phonenumber){

        return toAjax(userService.updatePhonenumber(phonenumber,userId));
    }

    //公告列表
    @RequestMapping("/noticeList")
    @ResponseBody
    public AjaxResult noticeList()
    {
        SysNotice sysNotice = new SysNotice();
        sysNotice.setStatus("0");
        return AjaxResult.success("查询成功",noticeService.selectNoticeList(sysNotice));
    }

    //公告详细
    @RequestMapping("/noticeById")
    @ResponseBody
    public AjaxResult noticeById(Long noticeId)
    {
        return AjaxResult.success("查询成功",noticeService.selectNoticeById(noticeId));
    }

    @RequestMapping("/selectMyTaskHome")
    @ResponseBody
    public AjaxResult selectMyTaskHome(Long userId)
    {
        Map returnMap = new HashMap();
        int yes_number = 0;
        int no_number = 0;
        List<AstTaskUser> list = taskUserService.selectAstTaskByUserId(userId);
        for(AstTaskUser taskUser : list){
            if(taskUser.getStatus().equals("1")){
                yes_number++;
            }else{
                no_number++;
            }
        }
        returnMap.put("yesNumber",yes_number);
        returnMap.put("noNumber",no_number);

        return AjaxResult.success("查询成功",returnMap);
    }

    @RequestMapping("/addDevice")
    @ResponseBody
    public AjaxResult addDevice(AstDevice device) throws Exception {
        SysUser sysUser = userService.selectUserById(device.getUserId());
        device.setCreateBy(sysUser.getUserName());
        device.setDeptId(sysUser.getDeptId());

        try {
            List<String> strings = deviceService.insertAstDevice(device);
            return AjaxResult.success("操作成功",strings);
        }catch (Exception e){
            return AjaxResult.error(e.toString());
        }
    }

    @RequestMapping("/storeroomList")
    @ResponseBody
    public AjaxResult storeroomList()
    {
        return AjaxResult.success("查询成功",storeroomService.selectAstStoreroomList(new AstStoreroom()));
    }

    //站点列表
    @RequestMapping("/siteList")
    @ResponseBody
    public AjaxResult siteList()
    {
        AstSite site = new AstSite();
        return AjaxResult.success("查询成功",siteService.selectAstSiteList(site));
    }

    @RequestMapping("/factoryList")
    @ResponseBody
    public AjaxResult factoryList()
    {
        return AjaxResult.success("查询成功",factoryService.selectAstFactoryList(new AstFactory()));
    }

    @RequestMapping("/selectMyCarryDevice")
    @ResponseBody
    public AjaxResult selectMyCarryDevice(Long userId){
        return AjaxResult.success("查询成功",deviceRecordService.selectMyCarryDevice(userId));
    }

    //扫码操作设备、、正常、暂停、报修、转移、归还、绑定站点等
    @RequestMapping("/caozuoDevice")
    @ResponseBody
    public AjaxResult caozuoDevice(AstDeviceRecord deviceRecord)
    {

        return toAjax(deviceService.caozuoDevice(deviceRecord));
    }

    //字典查询
    @RequestMapping("/selectDictData")
    @ResponseBody
    public AjaxResult selectDictData(String type)
    {
        SysDictData dictData = new SysDictData();
        dictData.setDictType(type);

        return AjaxResult.success("查询成功",dictDataService.selectDictDataList(dictData));
    }

    //扫码 查询设备信息
    @RequestMapping("/deviceInfoByQrcode")
    @ResponseBody
    public AjaxResult deviceInfoByQrcode(String deviceQrcode)
    {
        AstDevice device = deviceService.selectAstDeviceByQrcode(deviceQrcode);

        return AjaxResult.success("查询成功",device);
    }

    @RequestMapping("/selectMyTask")
    @ResponseBody
    public AjaxResult selectMyTask(Long userId)
    {
        return AjaxResult.success("查询成功",taskUserService.selectAstTaskByUserId(userId));
    }

    @RequestMapping("/selectMyTaskAndSite")
    @ResponseBody
    public AjaxResult selectMyTaskAndSite(Long userId)
    {
        List<AstTaskUser> list = taskUserService.selectAstTaskByUserId(userId);
        List<AstTaskUser> returnList = new ArrayList<>();

        for(AstTaskUser astTaskUser : list){
            if(astTaskUser.getStatus().equals("0")){
                List<AstTaskUser> taskAndSiteList = taskUserService.selectTaskUserlistList(astTaskUser.getAssignmentId());
                for(AstTaskUser taskAndSite : taskAndSiteList){
                    AstTaskUser returnTaskUser = new AstTaskUser();
                    returnTaskUser.setCreateBy(astTaskUser.getCreateBy());
                    returnTaskUser.setCreateTime(astTaskUser.getCreateTime());
                    returnTaskUser.setAssignmentId(astTaskUser.getAssignmentId());
                    returnTaskUser.setTaskId(astTaskUser.getTaskId());
                    returnTaskUser.setStatus(astTaskUser.getStatus());
                    returnTaskUser.setTaskDescribe(astTaskUser.getTaskDescribe());
                    returnTaskUser.setTaskDescribeZhu(astTaskUser.getTaskDescribeZhu());
                    returnTaskUser.setTaskName(astTaskUser.getTaskName());
                    returnTaskUser.setTaskType(astTaskUser.getTaskType());

                    returnTaskUser.setSiteId(taskAndSite.getSiteId());
                    returnTaskUser.setSiteName(taskAndSite.getSiteName());
                    returnTaskUser.setListId(taskAndSite.getListId());
                    returnTaskUser.setListStatus(taskAndSite.getListStatus());
                    returnList.add(returnTaskUser);
                }
            }
        }

        return AjaxResult.success("查询成功",returnList);
    }

    @RequestMapping("/selectMyTaskAndSiteById")
    @ResponseBody
    public AjaxResult selectMyTaskAndSiteById(Long assignmentId){
        List<AstTaskUser> taskAndSiteList = taskUserService.selectTaskUserlistList(assignmentId);
        return AjaxResult.success("查询成功",taskAndSiteList);
    }

    @RequestMapping("/deviceListBySiteId")
    @ResponseBody
    public AjaxResult deviceListBySiteId(Long siteId)
    {

        return AjaxResult.success("查询成功",deviceService.selectAstDeviceBySiteId(siteId));
    }

    @RequestMapping("/siteInfo")
    @ResponseBody
    public AjaxResult siteInfo(Long siteId)
    {
        return AjaxResult.success("查询成功",siteService.selectAstSiteBySiteId(siteId));
    }

    @RequestMapping("/myTaskInfo")
    @ResponseBody
    public AjaxResult myTaskInfo(Long assignmentId)
    {
        return AjaxResult.success("查询成功",taskUserService.selectAstTaskUserByAssignmentId(assignmentId));
    }

    @RequestMapping("/submitTask")
    @ResponseBody
    public AjaxResult submitTask(AstTaskUserList taskUserList)
    {

        return AjaxResult.success("提交成功",taskUserService.updateAstTaskUserList(taskUserList));
    }


    @RequestMapping("/updateSite")//???
    @ResponseBody
    public AjaxResult updateSite(AstSite site)
    {
        SysUser sysUser = userService.selectUserById(site.getUserId());

        AstSite newAstSite = new AstSite();
        newAstSite.setSiteId(site.getSiteId());
        newAstSite.setSiteJingwei(site.getSiteJingwei());
        siteService.updateAstSite(newAstSite);

        AstSiteRecord siteRecord = new AstSiteRecord();
        siteRecord.setStatus("3");
        siteRecord.setSiteId(site.getSiteId());
        siteRecord.setUserId(site.getUserId());
        siteRecord.setCreateTime(new Date());
        siteRecord.setCreateBy(sysUser.getUserName());
        siteRecord.setReason("修改站点信息");
        return AjaxResult.success("查询成功",siteRecordService.insertAstSiteRecord(siteRecord));
    }

    @RequestMapping("/xunjian")//???????
    @ResponseBody
    public AjaxResult xunjian(AstSiteRecord siteRecord)
    {
//        siteRecord.setStatus("0");
        if(siteRecord.getCreateTime() == null){
            siteRecord.setCreateTime(new Date());
        }
        SysUser sysUser = userService.selectUserById(siteRecord.getUserId());
        siteRecord.setCreateBy(sysUser.getUserName());

        return toAjax(siteService.xunjian(siteRecord));
    }


    //说明书列表
    @RequestMapping("/manualList")//
    @ResponseBody
    public AjaxResult manualList()
    {
        return AjaxResult.success("查询成功",manualService.selectAstManualList(new AstManual()));
    }

    //说明书详细
    @RequestMapping("/manualInfoById")//
    @ResponseBody
    public AjaxResult manualInfoById(Long manualId)
    {
        return AjaxResult.success("查询成功",manualService.selectAstManualByManualId(manualId));
    }

    //设备操作记录
    @RequestMapping("/deviceCaozuoList")
    @ResponseBody
    public AjaxResult deviceCaozuoList(Long deviceId)
    {
        return AjaxResult.success("查询成功",deviceRecordService.selectAstDeviceRecordListById(deviceId));
    }

    //我携带设备的记录
    @RequestMapping("/myHistoryXiedai")
    @ResponseBody
    public AjaxResult myHistoryXiedai(Long userId)
    {
        List<AstDeviceRecord> list = deviceRecordService.selectAstDeviceRecordListByUserId(userId);
        List returnList = new ArrayList();
        for(AstDeviceRecord deviceRecord : list){
            if(deviceRecord.getStatus().equals("0")){
                returnList.add(deviceRecord);
            }
        }
        return AjaxResult.success("查询成功",returnList);
    }

    //我报废设备的记录
    @RequestMapping("/myHistoryBaofei")
    @ResponseBody
    public AjaxResult myHistoryBaofei(Long userId)
    {
        List<AstDeviceRecord> list = deviceRecordService.selectAstDeviceRecordListByUserId(userId);
        List returnList = new ArrayList();
        for(AstDeviceRecord deviceRecord : list){
            if(deviceRecord.getStatus().equals("4")){
                returnList.add(deviceRecord);
            }
        }
        return AjaxResult.success("查询成功",returnList);
    }


    @PostMapping("/uploads")
    @ResponseBody
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }


}
